package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuyp
 * @since 2025/8/17
 */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果本次请求的目标资源不是Controller里的方法，则直接放行，不需要处理
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取本次请求携带的令牌
        String token = request.getHeader("authorization");

        //如果令牌为空，则直接返回401
        if (StringUtils.isEmpty(token)) {
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }

        //解析令牌
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtil.isEmpty(claims)) {
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }

        //获取令牌中的用户信息
        Long userId = claims.get("userId", Long.class);
        if (userId == null) {
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }

        //将用户id绑定到当前线程上
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}